package com.lcf.service.impl;

import com.lcf.annotation.ExtTransactional;
import com.lcf.dao.UserDao;
import com.lcf.service.LogService;
import com.lcf.service.UserService;
import com.lcf.transaction.TransactionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by lancf on 2019/4/25.
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    protected UserDao userDao;

    @Autowired
    protected LogService logService;

    @Autowired
    protected TransactionUtils transactionUtils;

    public void add(String name, int age) {

        TransactionStatus transactionStatus = null;
        try {
            transactionStatus = transactionUtils.begin();
            System.out.println("准备往数据库插入数据");
            userDao.addUser(name, age);
            System.out.println("往数据库插入数据");
            int i = 1 / 0;
            userDao.addUser("李四", 24);
            if (null != transactionStatus) {
                transactionUtils.commit(transactionStatus);
                System.out.println("success");
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (null != transactionStatus) {
                transactionUtils.rollback();
                System.out.println("success");
            }
            System.out.println("fail");
        }
    }

        @ExtTransactional
    public void add2(String name, int age) {
        userDao.addUser(name, age);
        int i = 1 / 0;
        userDao.addUser("李四", 24);
    }

    @Transactional
    @Override
    public void add3(String name, int age) {

        Map map = new HashMap();
        map.put("name:", name);
        map.put("age:", age);
        //添加日志
        logService.add(map.toString());
        userDao.addUser("赵六", 26);
        int i = 1 / 0;
        userDao.addUser("王五", 25);
    }

}
